package com.john.bms.config;

import com.john.bms.config.jwt.JwtConfiguration;
import io.jsonwebtoken.Claims;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;

/**
 * @Author:张家小帅哥
 * @Date:2020/9/20
 * @Version:1.0
 * @Description:TODO
 */
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

//    @Resource
//    private JwtConfiguration jwtConfiguration;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //从请求头中获取用户token（登陆凭证根据业务而定）
        String token = request.getHeader("X-Token");
        if (token == null) {
            throw new NullPointerException("token不存在");
        }
        Claims claims = JwtConfiguration.getTokenClaim(token);
        if (claims == null || JwtConfiguration.isTokenExpired(claims.getExpiration())) {
            throw new Exception("X-Token" + "失效，请重新登录");
        }
        //获取用户的sid
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        Serializable id = session.getId();
        System.out.println(id);
        if (id == null) {
            throw new UnknownAccountException("用户信息已过期!");
        }

        String uId = claims.getSubject();
        //解析到用户id后，先去redis中查找，查不到在去数据库中
//        Jedis jedis = new Jedis("localhost");
//        String idStatus = jedis.get(uId);
//        if (idStatus == null || "".equals(idStatus)) {
//            throw new UnknownAccountException("用户信息已过期!");
//        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}
